package com.springcloud.controller;

import com.netflix.discovery.EurekaClient;
import com.springcloud.pojo.Address;
import com.springcloud.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Random;

/**
 * @Author 咕唧
 * @Date 2022/6/23 17:07
 * @Version 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    private Random random = new Random();

    private RestTemplate restTemplate;

    private EurekaClient eurekaClient;

    @Autowired
    public void setEurekaClient(EurekaClient eurekaClient) {
        this.eurekaClient = eurekaClient;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/info/{id}")
    public Order findById(@PathVariable Long id) {
        Order order = new Order();
        order.setItemName("订单名字-----" + random.nextInt());
        order.setId(id);
        order.setPrice(random.nextDouble());

        //restTemplate已经整合好了，只需要在配置类中添加一个注解，就可以开启开启负载均衡了，默认访问方式为轮询
        Address address = restTemplate.getForObject("http://04ADDRESSPROVIDER/address/info/" + id, Address.class);
        order.setAddress(address);

        return order;
    }


    @GetMapping("/test/{id}")
    public String test(@PathVariable Long id) {
        //在注册中心使用随机负载均衡策略，查询两个地址中的对应的数据
        //这里同时查找同一个地址，由于对象创建模式为单例，会出现第二个查找到的端口地址 覆盖第一个的端口的地址的情况
        Address address = restTemplate.getForObject("http://04addressprovider/address/info/" + id, Address.class);
        System.err.println("11111111"+address);
        Address address2 = restTemplate.getForObject("http://04addressprovidera/address/test/" + id, Address.class);
        System.err.println("2222"+address2);
        return "success";
    }
}
